const fs = require('fs')

// const dbpath = './../pesist/db.json'
const db_user_path = './pesist/db_user.json'
const db_role_path = './pesist/db_role.json'


const { log: print } = console

const loadlist = function (attr) {
	let path = ''
	if (attr == 'userlist') {
		path = './pesist/db_user.json'
	} else if (attr == 'roledata') {
		path = './pesist/db_role.json'
	} else if (attr = 'rightslist') {
		path = './pesist/db_rights.json'
	}
	return new Promise((resolve, reject) => {
		fs.readFile(path, 'utf-8', (err, data) => {
			if (err) {
				reject(err)
			}
			const arr = JSON.parse(data)[attr]
			if (!Array.isArray(arr)) {
				reject(new Error('failed to decoding json'))
			}
			resolve(arr)
		})
	})
}

const writelist = function (attr, filedata) {
	let path = ''
	if (attr == 'userlist') {
		path = './pesist/db_user.json'
	} else if (attr == 'roledata') {
		path = './pesist/db_role.json'
	}
	return new Promise((resole, reject) => {
		fs.writeFile(path, filedata, (err) => {
			reject(err)
		})
		resole(null)
	})
}

// 用于用户名的模糊匹配
// new 创建的正则表达式好像只在第一次初始化时创建
const matchUser = function(str, arr) {
	if (!Array.isArray(arr)) {
		throw new Error('模糊匹配的对象不是数组！！')
	}
	const exp = new RegExp(str, 'g')
	return arr.filter(item => exp.test(item.username))
}





// --------- 模块导出 ---------
exports.find = function (name, callback) {
	loadlist(name).then(arr => callback(null, arr)).catch(err => callback(err))
}

exports.findById = function(name, id, callback) {
	loadlist(name)
		.then(arr => {
			const item = arr.find(it => it.id == id)
			callback(null, item)
		})
		.catch(err => callback(err))
}


// 这里的参数使用的是对象解构的默认值
// callback如过不报错，会传入三个参数，分别是null，查找出来的用户数组，以及pagenum和total组成的对象
exports.findWithFileter = function(name, { pagenum = 1, pagesize = 1, query = '' } = {}, callback) {
	loadlist(name)
		.then(arr => {
			const cap = arr.length
			while ((pagenum - 1) * pagesize >= cap) {
				pagenum--
			}
			let curIndexStart = pagenum - 1 ? (pagenum - 1) * pagesize : 0
			let curIndexEnd = curIndexStart + (pagesize - 0)

			// print(curIndexStart, curIndexEnd)
			// print(pagenum, pagesize, query)
			let ret = [], total = cap
			if (query !== '') {
				const temp = matchUser(query, arr)
				total = temp.length
				ret = temp.slice(curIndexStart, curIndexEnd)
				// print('query!')
			} else {
				// print('no query!')
				ret = arr.slice(curIndexStart, curIndexEnd)
			}
			// print(ret)
			callback(null, ret, { pagenum, total })
		})
		.catch(err => callback(err))
}

exports.update = function(name, id, info = {}, callback) {
	id = id - 0
	loadlist(name)
		.then(arr => {
			const index = arr.findIndex(it => it.id == id)
			// 逐个修改
			Object.keys(info).forEach(it => {
				if (arr[index].hasOwnProperty(it)) {
					arr[index][it] = info[it]
				}
			})
			let filedata = ''
			let path = ''
			if (name == 'userlist') {
				path = './pesist/db_user.json'
				filedata = JSON.stringify({ userlist: arr }, null, 2)
			} else if (name == 'roledata') {
				path = './pesist/db_role.json'
				filedata = JSON.stringify({ roledata: arr }, null, 2)
			}
			fs.writeFile(path, filedata, (err) => {
				if (err) {
					callback(err)
				}
				callback(null, arr[index])
			})
		})
		.catch(err => callback(err))
}


exports.adduser = function({ username = '', password = 'unknow', tel = '' } = {}, callback) {
	if (username === '' || password === '' || tel === '') {
		callback(new Error('添加数据失败！'))
	} else {
		loadlist('userlist')
		.then(arr => {
			const newRole = {
				id: arr[arr.length-1].id + 1,
				role_name: 'admin',
				username,
				tel,
				role_status: false
			}
			arr.push(newRole)
			const filedata = JSON.stringify({ userlist: arr }, null, 2)
			const path = './pesist/db_user.json'
			fs.writeFile(path, filedata, (err) => {
				if (err) {
					callback(err)
				}
				callback(null, newRole)
			})			
		})
		.catch(err => callback(err))
	}
}

exports.dropById = function(id, callback) {
	id = id - 0
	loadlist('userlist')
		.then(arr => {
			const index = arr.findIndex(it => it.id == id)
			if (index == -1) {
				callback(new Error('删除失败，原因在于找不到这个id对应的项'))
			}
			arr.splice(index, 1);
			const filedata = JSON.stringify({ userlist: arr }, null, 2)
			const path = './pesist/db_user.json'
			fs.writeFile(path, filedata, (err) => {
				if (err) {
					callback(err)
				}
				callback(null)
			})	
		})
		.catch(err => callback(err))
}
// loadlist('roledata').then(arr => print(arr)).catch(err => print(err))
